import {Injectable} from '@angular/core'
import {Observable} from 'rxjs/Rx'
import {User} from './user.model'
import {Http,Headers,RequestOptions} from '@angular/http';
import  'rxjs/Rx';
@Injectable()
export class UserService{
	//url:string="http://localhost:10000/users";
	url:string="/users";
	constructor(private http:Http){

	}
	findAllUsers():Observable<User[]>{
		return this.http.get(this.url)
				.map(res=>{
					var us=res.json();
					us.forEach(item=>{
						if(item._id) item.id=item._id;
					})
					return us;
				});
	}
	deleteUser(id:string):Observable<User>{
		return this.http.delete(this.url+"/"+id)
		.map(res=>res.json());
	}

	addUser(user:User):Observable<User>{
		var body=JSON.stringify(user);
		var headers=new Headers({"Content-Type":"application/json"});
		var requestOptions=new RequestOptions({headers:headers});
		return this.http.post(this.url,body,requestOptions)
		.map(res=>{
			var u=res.json();
			if(u._id) u.id=u._id;
			return u;
		});
	}

	updateUser(user:User):Observable<User>{
		var body=JSON.stringify(user);
		var headers=new Headers({"Content-Type":"application/json"});
		var requestOptions=new RequestOptions({headers:headers});
		return this.http.put(this.url+"/"+user.id,body,requestOptions)
			.map(res=>res.json() as User);
	}

}



















